package config;

import com.interceptor.FileTypeInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping;
import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;

@Configuration//主配置类
@ComponentScan("com.*")//指定扫描包，包下面的带有特殊注解的类都被spring初始化
@EnableWebMvc
@EnableTransactionManagement
@EnableScheduling
@EnableCaching
@Import({JdbcConfig.class, MyBatisConfig.class, FileUploadConfig.class,TransactionConfig.class,RedisConfig.class,CacheConfig.class,ShiroConfig.class})
public class SpringConfiguration extends WebMvcConfigurerAdapter {

    //BEAN 标签 调用产生bean方法得到对象，需要将原来xml版的 class做成 返回值，一般取名就是getXXX  xxx就是class名字，
    //简单操作就是 直接new ，new出的对象，设置属性，xml中有那些propertie需要设置，这边就调用对应的setXXX方法来设置
    @Bean("propertyConfigurer")
    public PropertyPlaceholderConfigurer getPropertyPalce(){
        PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = 	new PropertyPlaceholderConfigurer();
        ClassPathResource[]  classPathResources = {new ClassPathResource("c3p0.properties"),
                new ClassPathResource("log4jdbc.log4j2.properties"),new ClassPathResource("log4j.properties"),new ClassPathResource("redis.properties")};
        propertyPlaceholderConfigurer.setLocations(classPathResources);
        return propertyPlaceholderConfigurer;
    }



    @Bean
    public InternalResourceViewResolver getInternalResourceViewResolver() {
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setPrefix("/WEB-INF/jsp");
        internalResourceViewResolver.setSuffix(".jsp");
        return internalResourceViewResolver;
    }

    //配置 ResponseBoby 输出list对象的转换器，将jackson提供的转换器 设置给springmvc
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        MediaType[] supportedMediaTypes = {new MediaType("text", "html", Charset.forName("utf-8"))};

        converter.setSupportedMediaTypes(Arrays.asList(supportedMediaTypes));
//        for (MediaType mediaType : converter.getSupportedMediaTypes()) {
//            System.out.println(mediaType.getType() + "-----" + mediaType.getSubtype());
//        }
        messageConverters.set(6, converter);//为什么这个参数是6，因为默认7个类型转换器，他是第7个
//        int count = 0;
//        for (HttpMessageConverter httpMessageConverter : messageConverters) {
//            System.out.println(httpMessageConverter.getClass().getSimpleName() + "  --  " +count);
//            List<MediaType> mediaTypes = httpMessageConverter.getSupportedMediaTypes();
//            for (MediaType mediaType : mediaTypes) {
//                System.out.println(mediaType.getType() + " " + mediaType.getSubtype());
//            }
//            count++;
//        }
    }

//提供给url查找 赋值使用
    @Bean
    public BeanNameUrlHandlerMapping getBeanNameUrlHandlerMapping() {
        return new BeanNameUrlHandlerMapping();
    }

    @Bean
    public SimpleControllerHandlerAdapter
    getSimpleControllerHandlerAdapter() {
        return new SimpleControllerHandlerAdapter();
    }

    // 静态资源访问
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //addResourceHandler("/static/**") 表示将所有的static下的资源请映射到后面指定的路径.addResourceLocations("classpath:/static/")
        registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/").setCachePeriod(31556926);
        registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/").setCachePeriod(31556926);
        registry.addResourceHandler("/back/css/**").addResourceLocations("classpath:/static/back/css/").setCachePeriod(31556926);
        registry.addResourceHandler("/back/js/**").addResourceLocations("classpath:/static/back/js/").setCachePeriod(31556926);
        registry.addResourceHandler("/front/chart/css/**").addResourceLocations("classpath:/static/front/chart/css/").setCachePeriod(31556926);
        registry.addResourceHandler("/front/chart/js/**").addResourceLocations("classpath:/static/front/chart/js/").setCachePeriod(31556926);
        registry.addResourceHandler("/front/css/**").addResourceLocations("classpath:/static/front/css/").setCachePeriod(31556926);
        registry.addResourceHandler("/front/js/**").addResourceLocations("classpath:/static/front/js/").setCachePeriod(31556926);
        registry.addResourceHandler("/upload/**").addResourceLocations("/upload/").setCachePeriod(31556926);
        super.addResourceHandlers(registry);
        String os = System.getProperty("os.name");

        if (os.toLowerCase().startsWith("win")) {  //如果是Windows系统
            registry.addResourceHandler("/smallapple/**")
                    // /apple/**表示在磁盘apple目录下的所有资源会被解析为以下的路径
                    .addResourceLocations("file:G:/itemsource/smallapple/") //媒体资源
                    .addResourceLocations("classpath:/META-INF/resources/");  //swagger2页面
        } else {  //linux 和mac
            registry.addResourceHandler("/smallapple/**")
                    .addResourceLocations("file:/resources/smallapple/")   //媒体资源
                    .addResourceLocations("classpath:/META-INF/resources/");  //swagger2页面;
        }
    }

    /**
     * 注册自定义拦截器 如文件上传 类型 拦截器 大小拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new FileTypeInterceptor() {
        });
    }
}
